package com.qd.core.security.provider;

import com.qd.core.security.token.WxAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.StringUtils;

/**
 * 用户自定义身份认证, 短信验证码模式
 *
 * @author sjk
 */
@Slf4j
public class WxAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsService userDetailsService;

    /**
     * 认证处理，返回一个Authentication的实现类则代表认证成功，返回null则代表认证失败
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (log.isDebugEnabled()) {
            log.debug("WxAuthenticationProvider,name: {},principal: {},credentials: {}", authentication.getName(), authentication.getPrincipal(), authentication.getCredentials());
        }
        String rId = (String) authentication.getPrincipal();
        String unionId = (String) authentication.getCredentials();
        if (!StringUtils.hasLength(rId)) {
            throw new BadCredentialsException("关系ID不可以为空");
        }
        if (!StringUtils.hasLength(unionId)) {
            throw new BadCredentialsException("unionId不可以为空");
        }
        final UserDetails user = userDetailsService.loadUserByUsername(rId);
        return new WxAuthenticationToken(user, null, user.getAuthorities());
    }

    /**
     * 如果该AuthenticationProvider支持传入的Authentication对象，则返回true
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return WxAuthenticationToken.class.isAssignableFrom(aClass);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}